package com.scrcu.cloud.wechat.home.endpoint.auth.service;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.scrcu.cloud.wechat.home.endpoint.common.model.RestResponse;
import com.scrcu.cloud.wechat.home.endpoint.common.utils.HttpUtils;
import com.scrcu.cloud.wechat.home.endpoint.customer.service.Iml.UserServiceIml;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.logging.Logger;

@Service
@Slf4j
public class WxService {
    @Value("${tencent.msg.send.token}")
    private String token;

    /**
     * 获取access_token,每个公众账号一天请求2000次Access_Token
     * @return
     */

    /**
     * 消息推送配置 验证请求的合法性
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    public boolean checkSignature(String signature, String timestamp, String nonce) {
        // 小程序消息推送自己配置的token
        log.info("验证token:{}" + token);
        String[] arr = new String[]{token, timestamp, nonce};
        // 将token、timestamp、nonce三个参数进行字典序排序
        Arrays.sort(arr);
        // 将排序后的结果拼接成一个字符串
        String content = String.join("", arr);
        try {
            //获取加密工具
            MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
            // 使用SHA-1加密
            byte[] hashBytes = sha1.digest(content.getBytes());
            //将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : hashBytes) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            log.info("加密后signature：{}", hexString);
            // 将加密后的字符串与微信服务器提供的签名进行对比
            return hexString.toString().equals(signature);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // 如果签名不匹配，则返回false
        return false;
    }
}